package com.wrox.todolist;

import android.app.Fragment;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public class NewItemFragment extends Fragment {

	private Button buttonAdd;
	private EditText editAdd;
	private AddNewTodoItemListener newItemListener = null;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.new_item_fragment, container, false);
        buttonAdd = (Button) v.findViewById(R.id.button_add_new);
        editAdd = (EditText) v.findViewById(R.id.edit_add_new);
        buttonAdd.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				addItem();
			}
		});
        
        editAdd.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_DONE) {
					addItem();	
					return true;
				}
				return false;
			}
        	
        });
        return v;
	}

	public void setAddNewTodoItemListener(AddNewTodoItemListener l) {
		newItemListener = l;
	}
	
	private void addItem() {
		if (newItemListener != null && !editAdd.getText().toString().isEmpty())
			newItemListener.addNew(editAdd.getText().toString());
		editAdd.setText("");
	}
}
